import uuid

from flask import Blueprint, render_template, request, session
from werkzeug.utils import redirect

from app.froms import RegisterValidate, LoginValidate, AddArticle
from app.models import db, User, Article

blue = Blueprint('app',__name__)

@blue.route('/',methods=['GET'])
def index():
    return render_template('index.html')

@blue.route('/init_db/',methods=['GET'])
def init():
    db.create_all()
    return '创建成功'

@blue.route('/login/',methods=['GET','POST'])
def login():
    form = LoginValidate()
    if request.method == 'GET':
        return render_template('login.html',form=form)

    if request.method == 'POST':
        if form.validate_on_submit():
            name = request.form.get('username','')
            password = request.form.get('password','')
            name_from_db = User.query.filter(User.name==name).first().name
            password_from_db = User.query.filter(User.password==password).first().password
            if name==name_from_db and password == password_from_db:
                # res = redirect('/blog/index/')
                # token = uuid.uuid4().hex()
                # res.set_cookie('token',token,max_age=86400)
                # return res
                session['name']= name
                session['password'] = password
                user = User.query.filter(User.name==name).first()
                return render_template('index.html',form=form,user=user)
        return render_template('login.html', form=form)

@blue.route('/register/',methods=['GET','POST'])
def register():
    form = RegisterValidate()

    if request.method == 'GET':
        return render_template('register.html',form=form)

    if request.method == 'POST':
        if form.validate_on_submit():
            user = User()
            user.name = request.form.get('username','')
            # user.age = request.form.get('age','')
            user.password = request.form.get('password','')
            user.save()
            return render_template('index.html',form=form)

    return render_template('register.html')

@blue.route('/article/',methods=['GET','POST'])
def artic():
    if request.method == 'GET':
        return render_template('article.html')

@blue.route('/add/',methods=['GET','POST'])
def add():
    if request.method == 'GET':
       return render_template('add-article.html')

    if request.method == 'POST':
        form = AddArticle()

        title = request.form.get('title','')
        content = request.form.get('content','')
        artic = Article()
        artic.title = title
        artic.content = content
        db.session.add(artic)
        db.session.commit()
        hint = '提交成功'
    else:
        hint = '操作失败'
    return render_template('add-article.html',hint=hint)